
/**
 * Add events for touches and desktop devices and prevent move page in iphone.
 * Create custom Active state and prevent this active state by adding a data-activatable in your
 * html or data-preventactive also create a fast click by dispatching a custom event
 */
(function(){
    var has = "ontouchstart" in window,
        debugTimer = void(0),
        _oldItems = [],_oldPrevent = [],
        touches = {
            start: has ? "touchstart": "mousedown",
            touch: has ? "touch": "touch",
            move: has ? "touchmove": "mousemove",
            end: has ? "touchend": "mouseup",
            cancel: has ? "touchcancel": "mouseleave"
        },
        items, prevent;

    /**
     * function that dispatch custom event for fast click to item
     * @param item {Element}
     */
    function dispatchTouch(item){
        var event = document.createEvent("Event");
        event.initEvent(touches.touch, true, true);
        item.dispatchEvent(event);
    }

    /**
     * function that gets the element offset in page context
     * @param el {Element}
     * @returns {left, top}
     */
    function getElementPageOffset(el){
        var l = 0, t = 0;

        do{
            l += el.offsetLeft;
            t += el.offsetTop;
        }while(el = el.offsetParent);

        return {left:l, top:t};
    }

    /**
     * function that return first activatable parent element
     * @param item {Element}
     * @returns {Element} activatable element
     */
    function getParentActivatable(item){
        do{
            if(item.dataset["activatable"]) return item;
        }while(item = item.parentElement);
    }

    function update(){
        items = document.querySelectorAll("[data-activatable]");
        prevent = document.querySelectorAll("[data-preventactivatable]");
        /**
         * Add events to all activatable items
         */
        Array.prototype.forEach.call(items, function(item){
            if(Array.prototype.indexOf.call(_oldItems, item) > -1) return;
            item.addEventListener(touches.start, function(){
                /*var offset = getElementPageOffset(item);
                 item.offsetPageLeft = offset.left;
                 item.offsetPageTop = offset.top;*/
                item.classList.add("active");
            });
            item.addEventListener(touches.cancel, function(e){
                var active = document.querySelector(".active");
                if(active) active.classList.remove("active");
            });
            item.addEventListener(touches.end, function(e){
                doEnd(e);
            });
        });


        /**
         * Add start event and stopPropagation to prevent active
         */
        Array.prototype.forEach.call(prevent, function(item){
            if(Array.prototype.indexOf.call(_oldPrevent, item) > -1) return;
            item.addEventListener(touches.start, function(e){
                e.stopPropagation();
            });
        });

        _oldItems = items;
        _oldPrevent = prevent;
    }

    /**
     * Remove custom active state and dispatch fast click event if active item
     * is equal to current event item
     * @param e
     */
    function doEnd(e){
        var active = document.querySelector(".active"),
        //offset = getElementPageOffset(active),
            _item = getParentActivatable(e.target);
        //get parent activatable item and check if is equal to active element
        if(active ===  _item/* && (offset.left === _item.offsetPageLeft && offset.top === _item.offsetPageTop)*/) dispatchTouch(active);
        if(active) active.classList.remove("active");
    }


    update();


    /**
     * Prevent default move event to remove page moving on iphone
     */
    window.addEventListener(touches.move, function(e){
        e.preventDefault();
    });

    window.addEventListener("DOMNodeInserted", function(){
        //update();
    });

    window.addEventListener("updateActivatable", function(){
        update();
    });

})();

/**
 * Create scrolls for every element with data-scrollable="true"
 */
(function(){
    var items = document.querySelectorAll("[data-scrollable]");

    Array.prototype.forEach.call(items, function(item){
        var value = eval(item.dataset["scrollable"] || item.getAttribute("data-scrollable"));
        if(value){
            item.scroll = new iScroll(item, {
                hideScrollbar: false,
                checkDOMChanges: true,
                onRefresh: function(){
                    if(this.scrollerH <= this.wrapperH)
                        this.disable();
                    else
                        this.enable();
                },
                onBeforeScrollMove: function(){
                    var active;
                    if(active = this.wrapper.getElementsByClassName("active").item(0)){
                        active.classList.remove("active");
                    }
                }
            });
        }
    });
})();

!function(){
    //var url = "http://cinemacity.eu01.aws.af.cm";
    var url = "http://192.168.10.94:3000";
    var reload = false;
    var program = {};
    var _prev_loader_type;

    var ajax = {
        cinemas: new Ajax(),
        programs: new Ajax(),
        movie: new Ajax()
    };
    var list = {
        cinemas: document.getElementById("cinemas-list"),
        program: document.getElementById("program-list"),
        info: document.getElementById("movie-info")
    };
    var el = {
        cinema_name: document.getElementById("cinema-name"),
        date: document.getElementById("date"),
        loader: document.getElementById("loader"),
        title: document.getElementById("movie-title"),
        image: document.getElementById("movie-image"),
        select: document.getElementById("select-date"),
        filter: document.getElementById("filter-list"),
        mask: document.getElementById("mask"),
        alert: document.getElementById("alert-text"),
        movie: document.getElementById("movie-content"),
        desc: document.getElementById("movie-desc")
    };
    var pages = {
        menu: new Page(document.getElementById("cinemas")),
        main: new Page(document.getElementById("main")),
        program: new Page(document.getElementById("program")),
        movie: new Page(document.getElementById("movie")),
        alert: new Page(document.getElementById("alert"))
    };
    var buttons = {
        menu: document.getElementById("menu-button"),
        refresh: document.getElementById("refresh-button"),
        back: document.getElementById("back-button"),
        filter: document.getElementById("filter-button"),
        ok: document.getElementById("ok-button"),
        cancel: document.getElementById("cancel-button")
    };

    pages.main.addEventListener("onShow", function(){
        el.select.style.display = "";
        el.mask.style.display = "none";
        this.element.classList.remove("right");
    });
    pages.main.addEventListener("beforeHide", function(){
        el.select.style.display = "none";
        el.mask.style.display = "";
        this.element.classList.add("right");
    });
    pages.movie.addEventListener("beforeShow", function(){
        el.select.style.display = "none";
    });
    pages.movie.addEventListener("onHide", function(){
        el.select.style.display = "";
    });
    pages.menu.show();
    pages.program.show();
    pages.main.show();

    window.addEventListener("touchstart", function(){
        el.filter.classList.remove("visible");
    });
    window.addEventListener("mousedown", function(){
        el.filter.classList.remove("visible");
    });
    window.applicationCache.addEventListener('updateready', function(){
        el.alert.innerHTML = "<strong>Има ново обновление.</strong><br/><br/>Може да обновите приложението сега или то ще се обнови автоматично при следващо стартитране.";
        reload = true;
        pages.alert.show();
    });

    buttons.menu.addEventListener("touch", function(){
        if(pages.main.element.classList.contains("right")){
            pages.main.show("slide-left");
        }else{
            pages.main.hide("slide-right");
        }
    });
    buttons.refresh.addEventListener("touch", function(){
        refresh();
    });
    buttons.back.addEventListener("touch", function(){
        pages.movie.hide("scale-out-fade");
    });
    buttons.filter.addEventListener("touch", function(){
        el.filter.classList.toggle("visible");
    });
    buttons.ok.addEventListener("touch", function(){
        pages.alert.hide();
        if(reload){
            window.location.reload();
        }
    });
    buttons.cancel.addEventListener("touch", function(){
        pages.alert.hide();
    });
    el.mask.addEventListener("touch", function(){
        pages.main.show("slide-left");
    });

    loadDates();
    el.select.addEventListener("change", function(){
        showLoader("white");
        ajax.programs.get(url+ "/cinemas/" +program.cinema.id+ "/program/" +this.value);
    });

    ajax.programs.addEventListener("load", function(data, timestamp){
        hideLoader();
        loadProgram(data);
    });
    ajax.cinemas.addEventListener("load", function(data, timestamp){
        loadCinemas(data);
    });
    ajax.movie.addEventListener("load", function(data, timestamp){
        loadMovie(data);
    });
    ajax.programs.addEventListener("error", function(data, timestamp){
        hideLoader();
        loadProgram();
    });
    ajax.movie.addEventListener("error", function(data, timestamp){
        hideLoader();
        loadMovie();
    });
    ajax.cinemas.get(url+"/cinemas");

    function loadCinemas(data){
        var i = 0, li;
        for(i; i < data.length; i++){
            li = document.createElement("li");
            li.id = data[i].id;
            //li.dataset["activatable"] = true;
            li.setAttribute("data-activatable", true);
            li.innerHTML = "<div>"+data[i].name+"</div>";
            li.addEventListener("touch", function(){
                pages.main.show("slide-left");
                showLoader("white");
                ajax.programs.get(url+ "/cinemas/" +this.id+ "/program/" +getDate());
            }, true);
            list.cinemas.appendChild(li);
        }
        updateActivatables();
        //load first program
        showLoader("white");
        ajax.programs.get(url+ "/cinemas/" +data[0].id+ "/program/" +getDate());
    }
    function loadProgram(data){
        var i = 0, li, hours;
        program = data;
        if(!data){
            list.program.innerHTML = "";
            list.program.classList.add("problem");
            return;
        }else{
            list.program.classList.remove("problem");
        }
        el.select.value = data.date;
        el.cinema_name.innerHTML = data.cinema.name;
        el.date.innerHTML = data.date;

        list.program.innerHTML = "";
        if(data.movies.length == 0){
            list.program.classList.add("empty");
        }
        else{
            list.program.classList.remove("empty");
        }
        for(i; i < data.movies.length; i++){
            li = document.createElement("li");
            li.id = data.movies[i].id;
            li.dataset["activatable"] = true;
            li.setAttribute("data-activatable", true);
            li.innerHTML = "<div class='movie-name'>"+data.movies[i].name+"</div><div class='hours'><span>"+data.movies[i].hours.join(", ")+"<span></div>";
            (function(movie){
                li.addEventListener("touch", function(){
                    pages.movie.show("scale-in-appear");
                    showLoader("dark");
                    ajax.movie.get(url +"/movie/"+ movie.name);
                });
            })(data.movies[i]);
            list.program.appendChild(li);
        }
        updateActivatables();
    }
    function loadMovie(data){
        var i = 0, li, image = new Image();
        if(!data) {
            el.title.innerHTML = "";
            list.info.innerHTML = "";
            el.movie.classList.add("problem");
            return;
        }else{
            el.movie.classList.remove("problem");
        }
        el.title.innerHTML = data.title;
        el.desc.innerHTML = data.description;
        image.onload = function(){
            el.image.style.backgroundImage = "url("+this.src+")";
        };
        image.src = data.image;
        list.info.innerHTML = "";
        for(i; i < data.info.length; i++){
            li = document.createElement("li");
            li.innerHTML = "<strong>"+data.info[i].type+"</strong><span>"+data.info[i].value+"</span>";
            list.info.appendChild(li);
        }

        hideLoader();
    }
    function getDate(date){
        var d = date || new Date();
        return [d.getFullYear(), ("0"+(d.getMonth()+1)).slice(-2), ("0"+d.getDate()).slice(-2)].join("-");
    }
    function refresh(){
        if(!program) return;
        list.program.innerHTML = "";
        showLoader("white");
        ajax.programs.get(url+ "/cinemas/" +program.cinema.id+ "/program/" +program.date);
    }
    function showLoader(classname){
        el.loader.classList.remove(_prev_loader_type);
        el.loader.classList.add(_prev_loader_type = classname);
        el.loader.classList.add("visible");
    }
    function hideLoader(){
        el.loader.classList.remove("visible");
    }
    function loadDates(){
        var i, option, now = Date.now(), day = 86400000;

        for(i = 7; i > 0; i--){
            option = document.createElement("option");
            option.innerHTML = getDate(new Date(now-(day*i)));
            el.select.appendChild(option);
        }
        for(i = 0; i < 7; i++){
            option = document.createElement("option");
            option.innerHTML = getDate(new Date(now+(day*i)));
            el.select.appendChild(option);
        }
    }
    function updateActivatables(){
        var event = document.createEvent("Event");
        event.initEvent("updateActivatable", true, true);
        window.dispatchEvent(event);
    }
}();